package com.yungu.swift.order.processor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.JsonNode;
import com.yungu.swift.assets.driver.model.dto.DriverCommissionConfigDto;
import com.yungu.swift.assets.driver.model.dto.DriverDto;
import com.yungu.swift.assets.driver.model.dto.DriverStatusCycleDto;
import com.yungu.swift.assets.driver.model.vo.DriverVo;
import com.yungu.swift.assets.driver.service.DriverQueueService;
import com.yungu.swift.assets.driver.service.DriverService;
import com.yungu.swift.assets.driver.service.DriverStatusCycleService;
import com.yungu.swift.assets.passenger.model.dto.PassengerDto;
import com.yungu.swift.assets.passenger.model.vo.PassengerVo;
import com.yungu.swift.assets.passenger.service.PassengerService;
import com.yungu.swift.autoconfig.redis.RedisStringCacheService;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.constants.CommonConstant;
import com.yungu.swift.constants.DriverConstant;
import com.yungu.swift.constants.OrderConstant;
import com.yungu.swift.lbs.model.Coordinate;
import com.yungu.swift.lbs.service.DistanceService;
import com.yungu.swift.lbs.service.LocationService;
import com.yungu.swift.order.consts.Constants;
import com.yungu.swift.order.dao.OrderDetailMapper;
import com.yungu.swift.order.dao.OrderFareMapper;
import com.yungu.swift.order.dao.OrderMapper;
import com.yungu.swift.order.model.dto.OrderDetailDto;
import com.yungu.swift.order.model.dto.OrderDto;
import com.yungu.swift.order.model.dto.OrderFareDto;
import com.yungu.swift.order.model.param.CrosstownOrderParam;
import com.yungu.swift.order.model.vo.AllPassengerOrderVo;
import com.yungu.swift.order.model.vo.PayVo;
import com.yungu.swift.order.service.OrderDetailService;
import com.yungu.swift.order.service.OrderFareService;
import com.yungu.swift.order.service.OrderJoinService;
import com.yungu.swift.order.service.OrderService;
import com.yungu.swift.order.thread.driver.status.DriverStatusCycleRunnable;
import com.yungu.swift.order.utils.SendMessageUtils;
import com.yungu.swift.order.utils.ThreadExecutorUtils;
import com.yungu.swift.socket.push.model.PushContent;
import com.yungu.swift.socket.push.service.PushService;
import com.yungu.swift.system.finance.model.dto.FinancePrepayDto;
import com.yungu.swift.system.finance.service.FinancePrepayService;
import com.yungu.swift.system.sys.model.dto.SysAssignConfigDto;
import com.yungu.swift.system.sys.model.dto.SysWayDto;
import com.yungu.swift.system.sys.service.SysWayService;
import com.yungu.swift.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static com.yungu.swift.constants.OrderConstant.*;
import static com.yungu.swift.order.helper.OrderHelper.*;
import static com.yungu.swift.order.model.enums.OrderErrorEnum.ORDER_CROSS_STATUS_CHANGE_ERROR;
import static com.yungu.swift.order.model.enums.OrderErrorEnum.ORDER_CROSS_STATUS_CHANGE_ORDER_CLOSE;

/**
 * 跨城订单相关处理
 */
@Slf4j
@Component
public class CrosstownOrderProcessor {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderFareMapper orderFareMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderJoinService orderJoinService;
    @Autowired
    private CommissionProcessor commissionProcessor;
    @Autowired
    private OrderFareService orderFareService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private RedisStringCacheService redisStringCacheService;

    @Reference
    private DriverService driverService;
    @Reference
    private PassengerService passengerService;
    @Reference
    private FinancePrepayService financePrepayService;
    @Reference
    private DriverStatusCycleService driverStatusCycleService;
    @Reference
    private LocationService locationService;
    @Reference
    private DistanceService distanceService;
    @Reference
    private PushService pushService;
    @Reference
    private DriverQueueService driverQueueService;
    @Reference
    private SysWayService sysWayService;

    /**
     * 行程开始 410
     */
    public ResponseData tripBegan(CrosstownOrderParam crosstownOrderParam) {
        OrderDto mainOrder = findOrder(crosstownOrderParam.getMainOrderUuid());
        //订单信息校验
        ResponseData orderInfoVerifyResult = orderInfoVerify(mainOrder, crosstownOrderParam.getJoinStatus());
        if (!orderInfoVerifyResult.isSuccess()) {
            return orderInfoVerifyResult;
        }
        //关闭订单与司机出发互斥操作
        ResponseData lockRsd = handleLock(crosstownOrderParam.getMainOrderUuid());
        if (!lockRsd.isSuccess()) {
            return lockRsd;
        }
        //校验是否有扫码下单未支付订单
        int scanOrderNoPay = orderMapper.checkScanCodeOrderNoPay(mainOrder.getUuid());
        if (scanOrderNoPay > 0) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "乘客未支付扫码订单，请提醒乘客支付！");
        }
        //手动插入定位点
        if (!uploadTextResult(crosstownOrderParam.getUploadText())) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "上传定位点失败");
        }
        //更新主单与子单的订单状态
        orderMapper.updateStatusByJoinOrderRelatedUuid(mainOrder.getUuid(), OrderConstant.ORDER_JOIN_STATUS_DRIVER_DEPARTURE);
        //更新订单费用的出发时间
        Map<String, Object> updateOrderFareMap = new HashMap<>();
        updateOrderFareMap.put("mainOrderUuid", mainOrder.getUuid());
        updateOrderFareMap.put("driDepartTime", new Date());
        orderFareMapper.batchUpdateRelatedByMainOrderUuid(updateOrderFareMap);

        //获取所有订单信息
        List<AllPassengerOrderVo> orderList = getAllPassengerOrder(crosstownOrderParam);

        //乘客经纬度
        List<String> passengerOriginLngLat = new ArrayList<>();
        for (AllPassengerOrderVo orderDetailVo : orderList) {
            //构造乘客出发地经纬度参数
            passengerOriginLngLat.add(orderDetailVo.getOriginLng() + "," + orderDetailVo.getOriginLat());
        }
        //批量查询订单与司机距离信息 根据距离对订单进行排序
        ResponseData<List<Double>> responseData = distanceService.getBatchDistance(
                crosstownOrderParam.getDriverLng() + "," + crosstownOrderParam.getDriverLat(), passengerOriginLngLat);
        if (responseData.isSuccess() && responseData.getData() != null) {
            List<CrosstownOrderParam> crosstownOrderParamList = new ArrayList<>();
            for (int i = 0; i < responseData.getData().size(); i++) {
                CrosstownOrderParam updateSequenceOrder = new CrosstownOrderParam();
                updateSequenceOrder.setOrderUuid(orderList.get(i).getOrderUuid());
                updateSequenceOrder.setDistance(responseData.getData().get(i));
                crosstownOrderParamList.add(updateSequenceOrder);
            }
            crosstownOrderParamList.sort(Comparator.comparing(CrosstownOrderParam::getDistance, Comparator.nullsLast((v1, v2) -> v1.compareTo(v2))));
            int handleSequence = 1;
            for (CrosstownOrderParam updateSequenceOrder : crosstownOrderParamList) {
                updateSequenceOrder.setHandleSequence(handleSequence);
                handleSequence++;
            }
            if (CollectionUtils.isNotEmpty(crosstownOrderParamList)) {
                orderMapper.orderSequenceChange(crosstownOrderParamList);
            }
        } else {
            log.info("主订单：{} 调用高德批量接口距离测算失败", crosstownOrderParam.getMainOrderUuid());
        }
        //推送给各个乘客
        for (AllPassengerOrderVo orderDetailVo : orderList) {
            /*消息推送*/
            Map<String, Object> data = MapUtils.build();
            data.put("orderUuid", orderDetailVo.getOrderUuid());
            data.put("title", "订单行程开始通知");
            data.put("typeModule", orderDetailVo.getTypeModule());
            String content;
            //小件订单
            if (orderDetailVo.getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
                content = "行程开始：您的寄件订单，时间：" + DateUtils.format(orderDetailVo.getDeparTime()) + "，司机已经出发来取件，请提前准备好货件！";
            } else {
                content = "行程开始：您的用车订单，出发时间：" + DateUtils.format(orderDetailVo.getDeparTime()) + "，司机已经出发前来接驾，请提前做好上车准备！";
            }
            data.put("content", content);
            PushContent pushContent = PushContent.newInstance4Pas(crosstownOrderParam.getAppid(), PushContent.ORDER_JOIN_PAS_ORDER_DRIVER_DEPARTURE, data);
            pushService.sendMessage(orderDetailVo.getPassengerUuid(), pushContent);
        }

        try{
            ThreadExecutorUtils.execute(()->{
                SysWayDto sysWayDto = sysWayService.list(MapUtils.build("uuid",mainOrder.getWayUuid())).getData().get(0);
                DriverDto driverDto = driverService.get(mainOrder.getActualDriverUuid()).getData();
                //如果司机下班了  设置为上班
                if(DriverConstant.DRIVER_IS_NOT_WORK.equals(driverDto.getIsWork())){
                    log.info("主动设置司机出车：{},mianOrderUuid{}",driverDto.getUuid(),mainOrder.getUuid());
                    driverQueueService.queueUp(mainOrder.getAppid(),driverDto.getUuid(),null,null,crosstownOrderParam.getUploadText(),null,sysWayDto.getDestSiteUuid());
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        //保存行程类型
        orderMapper.saveTaskModel(mainOrder.getUuid(),crosstownOrderParam.getTaskModel());

        // 记录状态周期
        ThreadExecutorUtils.execute(new DriverStatusCycleRunnable(
                driverStatusCycleService,
                locationService,
                mainOrder.getAppid(),
                mainOrder.getActualDriverUuid(), mainOrder.getUuid(),
                mainOrder.getCarUuid(),
                DriverStatusCycleDto.ACTION_LEAVE));

        return orderJoinService.crosstownOrderListDetail(crosstownOrderParam);
    }

    /**
     * 司机到达上车地点 420
     */
    public ResponseData arriveGetOnPoint(CrosstownOrderParam crosstownOrderParam) {
        OrderDto orderDto = findOrder(crosstownOrderParam.getOrderUuid());
        //订单信息校验
        ResponseData orderInfoVerifyResult = orderInfoVerify(orderDto, crosstownOrderParam.getJoinStatus());
        if (!orderInfoVerifyResult.isSuccess()) {
            return orderInfoVerifyResult;
        }
        //手动插入定位点
        if (!uploadTextResult(crosstownOrderParam.getUploadText())) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "上传定位点失败");
        }
        OrderDto udpOrderDto = new OrderDto();
        udpOrderDto.setUuid(orderDto.getUuid());
        udpOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_ARRIVE_POINT);

        orderMapper.edit(udpOrderDto);

        //更新订单费用的司机到达时间
        OrderFareDto orderFareDto = new OrderFareDto();
        orderFareDto.setOrderUuid(orderDto.getUuid());
        orderFareDto.setDriArrTime(new Date());
        orderFareMapper.edit(orderFareDto);

        /*消息推送*/
        Map<String, Object> data = MapUtils.build();
        data.put("orderUuid", orderDto.getUuid());
        data.put("title", "司机到达上车点通知");
        data.put("typeModule", orderDto.getTypeModule());
        String content;
        //小件订单
        if (orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
            content = "司机已到达取件地点，请尽快将货件送达！";
        } else {
            content = "司机已到达上车地点，请尽快上车";
        }
        data.put("content", content);
        PushContent pushContent = PushContent.newInstance4Pas(crosstownOrderParam.getAppid(), PushContent.ORDER_JOIN_PAS_ORDER_ARRIVE_POINT, data);
        pushService.sendMessage(orderDto.getPassengerUuid(), pushContent);
        return orderJoinService.crosstownOrderListDetail(crosstownOrderParam);
    }

    /**
     * 乘客上车 430
     */
    public ResponseData passengerGetOn(CrosstownOrderParam crosstownOrderParam) {
        OrderDto orderDto = findOrder(crosstownOrderParam.getOrderUuid());
        //订单信息校验
        ResponseData orderInfoVerifyResult = orderInfoVerify(orderDto, crosstownOrderParam.getJoinStatus());
        if (!orderInfoVerifyResult.isSuccess()) {
            return orderInfoVerifyResult;
        }
        //手动插入定位点
        if (!uploadTextResult(crosstownOrderParam.getUploadText())) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "上传定位点失败");
        }
        OrderDto udpOrderDto = new OrderDto();
        udpOrderDto.setUuid(orderDto.getUuid());
        udpOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_PASSENGER_ABOARD);
        orderMapper.edit(udpOrderDto);

        //更新订单费用的司机到达时间
        OrderFareDto orderFareDto = new OrderFareDto();
        orderFareDto.setOrderUuid(orderDto.getUuid());
        orderFareDto.setPasArrTime(new Date());
        orderFareMapper.edit(orderFareDto);

        //校验乘客是否都已上车 若是 则更新主订单状态
        boolean isComplete = verifyOrderStatus(OrderConstant.ORDER_JOIN_STATUS_ARRIVE_POINT, orderDto.getMainOrderUuid());
        if (isComplete) {
            //获取所有订单信息
            List<AllPassengerOrderVo> orderList = getAllPassengerOrder(crosstownOrderParam);
            //乘客经纬度
            List<String> passengerOriginLngLat = new ArrayList<>();
            for (AllPassengerOrderVo orderDetailVo : orderList) {
                //构造乘客出发地经纬度参数
                passengerOriginLngLat.add(orderDetailVo.getDestLng() + "," + orderDetailVo.getDestLat());
            }
            ResponseData<List<Double>> batchDistance = distanceService.getBatchDistance(
                    crosstownOrderParam.getDriverLng() + "," + crosstownOrderParam.getDriverLat(), passengerOriginLngLat);
            if (batchDistance.isSuccess() && CollectionUtils.isNotEmpty(batchDistance.getData())) {
                List<CrosstownOrderParam> crosstownOrderParamList = new ArrayList<>();
                for (int i = 0; i < batchDistance.getData().size(); i++) {
                    CrosstownOrderParam updateSequenceOrder = new CrosstownOrderParam();
                    updateSequenceOrder.setOrderUuid(orderList.get(i).getOrderUuid());
                    updateSequenceOrder.setDistance(batchDistance.getData().get(i));
                    crosstownOrderParamList.add(updateSequenceOrder);

                }
                crosstownOrderParamList.sort(Comparator.comparing(CrosstownOrderParam::getDistance, Comparator.nullsLast((v1, v2) -> v1.compareTo(v2))));
                int handleSequence = 1;
                for (CrosstownOrderParam updateSequenceOrder : crosstownOrderParamList) {
                    log.info("订单：{} 距离：{}", crosstownOrderParam.getOrderUuid(), updateSequenceOrder.getDistance());
                    updateSequenceOrder.setHandleSequence(handleSequence);
                    handleSequence++;
                }
                orderMapper.orderSequenceChange(crosstownOrderParamList);
            } else {
                log.info("主订单：{} 调用高德批量接口距离测算失败", crosstownOrderParam.getMainOrderUuid());
            }
        }

        /*消息推送*/
        Map<String, Object> data = MapUtils.build();
        data.put("orderUuid", orderDto.getUuid());
        data.put("title", "司机接到乘客通知");
        data.put("typeModule", orderDto.getTypeModule());
        String content;
        //小件订单
        if (orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
            content = "您的货件已被司机接收！";
            //发送收件码给收件人
            OrderDetailDto orderDetailDto = orderDetailService.get(MapUtils.build("orderUuid", orderDto.getUuid())).getData();
            SendMessageUtils.generalSend(orderDetailDto.getReceiverMobile(), "您有一个由手机号码：" + orderDetailDto.getSenderMobile() + "，名称：" + orderDetailDto.getSenderName()
                    + "寄出的货件，收件码：【" + orderDetailDto.getReceiptCode() + "】,请在货件送达时,告知司机确认，并检查货件信息无误", orderDto.getAppid());
        } else {
            content = "您已上车！";
        }
        data.put("content", content);
        PushContent pushContent = PushContent.newInstance4Pas(crosstownOrderParam.getAppid(), PushContent.ORDER_JOIN_PAS_ORDER_ABOARD, data);
        pushService.sendMessage(orderDto.getPassengerUuid(), pushContent);

        //通知推送拼友
        pushOtherPassenger(crosstownOrderParam);

        if (isComplete) {
            //全部上车时 记录状态周期
            ThreadExecutorUtils.execute(new DriverStatusCycleRunnable(
                    driverStatusCycleService,
                    locationService,
                    orderDto.getAppid(),
                    orderDto.getActualDriverUuid(), orderDto.getMainOrderUuid(),
                    orderDto.getCarUuid(),
                    DriverStatusCycleDto.ACTION_RIDE));
        }

        return orderJoinService.crosstownOrderListDetail(crosstownOrderParam);
    }

    /**
     * 到达目的地
     */
    public ResponseData arriveDestination(CrosstownOrderParam crosstownOrderParam) {

        OrderDto orderDto = findOrder(crosstownOrderParam.getOrderUuid());
        //订单信息校验
        ResponseData orderInfoVerifyResult = orderInfoVerify(orderDto, crosstownOrderParam.getJoinStatus());
        if (!orderInfoVerifyResult.isSuccess()) {
            return orderInfoVerifyResult;
        }

        //如果是小件订单 需要校验收件码是否正确
        if (orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
            if (StringUtils.isEmpty(crosstownOrderParam.getReceiptCode())) {
                return ResponseData.buildErrorResponse(0, "收件码不能为空");
            }
            Map<String, Object> paraMap = new HashMap<>(4);
            paraMap.put("orderUuid", orderDto.getUuid());
            paraMap.put("receiptCode", crosstownOrderParam.getReceiptCode());
            List<OrderDetailDto> verifyList = orderDetailMapper.list(paraMap);
            if (verifyList == null || verifyList.size() == 0) {
                return ResponseData.buildErrorResponse(0, "收件码验证失败，请核对后重新填入");
            }
        }

        //手动插入定位点
        if (!uploadTextResult(crosstownOrderParam.getUploadText())) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "上传定位点失败");
        }

        List<OrderDetailDto> detailList = orderDetailMapper.list(MapUtils.build("orderUuid", orderDto.getUuid()));
        if (CollectionUtils.isEmpty(detailList)) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "订单详情未找到");
        }
        OrderDetailDto orderDetailDto = detailList.get(0);
        // 保存录音信息
        OrderDetailDto updDetailDto = new OrderDetailDto();
        updDetailDto.setUuid(orderDetailDto.getUuid());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String tripRecording = sdf.format(orderDetailDto.getDeparTime()) + "/" + orderDto.getMainOrderUuid() + ".mp3";
        updDetailDto.setTripRecording(tripRecording);
        updDetailDto.setUpdateOn(new Date());
        CompletableFuture.runAsync(() -> orderDetailService.edit(updDetailDto));

        //更新订单状态
        OrderDto udpOrderDto = new OrderDto();
        udpOrderDto.setUuid(orderDto.getUuid());
        OrderFareDto orderFareDto = new OrderFareDto();
        //先付费订单 到达目的时 直接完成订单 后付费订单 进入确认费用界面
        if (OrderConstant.ORDER_PAY_PATTERN_FRONT.equals(orderDto.getPayPattern())) {
            //先付费订单 到达目的地直接确认费用
            orderFareDto.setConfirmTime(new Date());
            udpOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_COMPLETED);
            //进场订单费用结算 计算司机抽成等
            ResponseData calcuFareRsd = orderFareSettlement(orderDto);
            if (!calcuFareRsd.isSuccess()) {
                //结算失败
                return calcuFareRsd;
            }
        } else {
            udpOrderDto.setPayStatus(Constants.ORDER_PAY_STATUS_UNPAY);
            udpOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_CONFIRM_FARE);
        }
        orderMapper.edit(udpOrderDto);

        //更新订单费用的司机到达时间
        orderFareDto.setOrderUuid(orderDto.getUuid());
        orderFareDto.setArriveTime(new Date());
        orderFareMapper.edit(orderFareDto);

        //判断乘客是否是首单 是则在乘客表打上标记
        try {
            int isFirstOrder = orderMapper.checkPassengerFirstOrder(orderDto.getPassengerUuid(), orderDto.getUuid());
            if (isFirstOrder == 0) {
                PassengerDto passengerDto = new PassengerDto();
                passengerDto.setUuid(orderDto.getPassengerUuid());
                passengerDto.setFirstOrderUuid(orderDto.getUuid());
                passengerService.edit(passengerDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //更新主订单价格表
        List<OrderFareDto> list = orderFareMapper.list(MapUtils.build("orderUuid", orderDto.getMainOrderUuid()));
        if (null == list || list.isEmpty()) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取主订单费用信息异常");
        }

        //校验乘客是否都已到达目的地 若是 则更新主订单状态
        boolean isComplete = verifyOrderStatus(OrderConstant.ORDER_JOIN_STATUS_STARTED, orderDto.getMainOrderUuid());

        /*消息推送*/
        Map<String, Object> data = MapUtils.build();
        data.put("orderUuid", orderDto.getUuid());
        data.put("title", "订单完成通知");
        data.put("typeModule", orderDto.getTypeModule());
        String content;
        //小件订单
        if (orderDto.getTypeModule() == CommonConstant.BUSINESS_TYPE_PARCEL) {
            content = "您的货件已送达，欢迎下次继续使用！";
        } else {
            content = "已将您送达目的地，欢迎下次乘坐！";
        }
        data.put("content", content);
        PushContent pushContent = PushContent.newInstance4Pas(crosstownOrderParam.getAppid(), PushContent.ORDER_JOIN_PAS_ORDER_COMPLETE, data);
        pushService.sendMessage(orderDto.getPassengerUuid(), pushContent);

        //通知推送拼友
        pushOtherPassenger(crosstownOrderParam);
        try{
            ThreadExecutorUtils.execute(()->{
                Map<String, Object> verifyMap = new HashMap<>();
                verifyMap.put("mainOrderUuid", orderDto.getMainOrderUuid());
                verifyMap.put("joinStatus", OrderConstant.ORDER_JOIN_STATUS_CONFIRM_FARE);
                int notArrive = orderMapper.verifyCrosstownOrderStatus(verifyMap);
                if(notArrive==0){
                    log.info("订单：mainOrderUuid{}已全部到达目的地,开始主动收车",orderDto.getMainOrderUuid());
                    DriverDto driverDto = driverService.get(orderDto.getActualDriverUuid()).getData();
                    //如果司机下班了  设置为上班
                    if(DriverConstant.DRIVER_IS_WORK.equals(driverDto.getIsWork())){
                        Double lng = 0d;
                        Double lat = 0d;
                        try {
                            JsonNode json = JsonUtils.readNode(crosstownOrderParam.getUploadText());
                            lng = json.get("lng").asDouble();
                            lat = json.get("lat").asDouble();
                            log.info("主动设置司机收车：{},orderUuid{},使用uploadText",driverDto.getUuid(),orderDto.getUuid());
                        }catch (Exception e){
                            e.printStackTrace();
                            log.info("主动设置司机收车：{},orderUuid{},使用订单终点经纬度",driverDto.getUuid(),orderDto.getUuid());
                            lng = orderDetailDto.getDestLng();
                            lat = orderDetailDto.getDestLat();
                        }
                        Coordinate coordinate = new Coordinate();
                        coordinate.setLng(lng);
                        coordinate.setLat(lat);
                        log.info("主动设置司机收车：{},orderUuid{}",driverDto.getUuid(),orderDto.getUuid());
                        driverQueueService.quit(driverDto.getUuid(),coordinate);
                    }
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
        if (isComplete) {
            //全部到达时 记录状态周期
            ThreadExecutorUtils.execute(new DriverStatusCycleRunnable(
                    driverStatusCycleService,
                    locationService,
                    orderDto.getAppid(),
                    orderDto.getActualDriverUuid(), orderDto.getMainOrderUuid(),
                    orderDto.getCarUuid(),
                    DriverStatusCycleDto.ACTION_SERVICE_OVER));

        }

        return orderJoinService.crosstownOrderListDetail(crosstownOrderParam);
    }

    /**
     * 司机选择收现，更新为司机支付状态
     */
    public ResponseData<Map<String, Object>> makeDriverPay(CrosstownOrderParam crosstownOrderParam) {

        OrderDto orderDto = findOrder(crosstownOrderParam.getOrderUuid());
        //订单信息校验
        ResponseData orderInfoVerifyResult = orderInfoVerify(orderDto, crosstownOrderParam.getJoinStatus());
        if (!orderInfoVerifyResult.isSuccess()) {
            return orderInfoVerifyResult;
        }

        OrderDto udpOrderDto = new OrderDto();
        udpOrderDto.setUuid(orderDto.getUuid());
        udpOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_DRIVER_PAY);
        orderMapper.edit(udpOrderDto);

        //更新订单确认费用时间
        OrderFareDto orderFareDto = new OrderFareDto();
        orderFareDto.setOrderUuid(orderDto.getUuid());
        orderFareDto.setConfirmTime(new Date());
        //计算附加费
        calAdditionalFare(crosstownOrderParam, orderFareDto);
        orderFareMapper.edit(orderFareDto);

        //校验乘客是否都为确认费用之后的状态 若是 则更新主订单状态未部分未支付状态
        boolean isComplete = verifyOrderStatus(orderDto.getJoinStatus(), orderDto.getMainOrderUuid());

        /*消息推送*/
        Map<String, Object> data = MapUtils.build();
        data.put("orderUuid", orderDto.getUuid());
        data.put("title", "司机收现");
        data.put("typeModule", orderDto.getTypeModule());
        data.put("content", "司机收现，正在等待司机操作");
        PushContent pushContent = PushContent.newInstance4Pas(crosstownOrderParam.getAppid(), PushContent.ORDER_JOIN_PAS_ORDER_WAIT_DRIVER_PAY, data);
        pushService.sendMessage(orderDto.getPassengerUuid(), pushContent);

        if (isComplete) {
            //全部到达时 记录状态周期
            ThreadExecutorUtils.execute(new DriverStatusCycleRunnable(
                    driverStatusCycleService,
                    locationService,
                    orderDto.getAppid(),
                    orderDto.getActualDriverUuid(), orderDto.getMainOrderUuid(),
                    orderDto.getCarUuid(),
                    DriverStatusCycleDto.ACTION_SERVICE_OVER));
        }

        return ResponseData.buildSuccessResponse("操作成功", null);
    }

    /**
     * 计算附加费
     */
    private void calAdditionalFare(CrosstownOrderParam crosstownOrderParam, OrderFareDto editOrderFare) {
        //设置高速费 其他费等
        Integer additionalFare = 0;
        if (crosstownOrderParam.getHighwayFare() > 0) {
            editOrderFare.setHighwayFare(crosstownOrderParam.getHighwayFare());
            additionalFare += crosstownOrderParam.getHighwayFare();
        }
        if (crosstownOrderParam.getExcessBaggageFare() > 0) {
            editOrderFare.setExcessBaggageFare(crosstownOrderParam.getExcessBaggageFare());
            additionalFare += crosstownOrderParam.getExcessBaggageFare();
        }
        if (crosstownOrderParam.getOtherFare() > 0) {
            editOrderFare.setOtherFare(crosstownOrderParam.getOtherFare());
            additionalFare += crosstownOrderParam.getOtherFare();
        }
        //存在附加费时 取出
        if (additionalFare > 0) {
            OrderFareDto curOrderFare = orderFareMapper.list(MapUtils.build("orderUuid", crosstownOrderParam.getOrderUuid())).get(0);
            editOrderFare.setTotalFare(curOrderFare.getTotalFare() + additionalFare);
        }
    }

    /**
     * 司机选择乘客支付，更新为乘客支付状态
     */
    public ResponseData<Map<String, Object>> makePassengerPay(CrosstownOrderParam crosstownOrderParam) {

        OrderDto orderDto = findOrder(crosstownOrderParam.getOrderUuid());
        //订单信息校验
        ResponseData orderInfoVerifyResult = orderInfoVerify(orderDto, crosstownOrderParam.getJoinStatus());
        if (!orderInfoVerifyResult.isSuccess()) {
            return orderInfoVerifyResult;
        }

        OrderDto udpOrderDto = new OrderDto();
        udpOrderDto.setUuid(orderDto.getUuid());
        udpOrderDto.setJoinStatus(OrderConstant.ORDER_JOIN_STATUS_PASSENGER_PAY);
        orderMapper.edit(udpOrderDto);

        //更新订单确认费用时间
        OrderFareDto orderFareDto = new OrderFareDto();
        orderFareDto.setOrderUuid(orderDto.getUuid());
        orderFareDto.setConfirmTime(new Date());
        //计算附加费
        calAdditionalFare(crosstownOrderParam, orderFareDto);
        orderFareMapper.edit(orderFareDto);

        //校验乘客是否都为确认费用之后的状态 若是 则更新主订单状态未部分未支付状态
        boolean isComplete = verifyOrderStatus(orderDto.getJoinStatus(), orderDto.getMainOrderUuid());

        /*消息推送*/
        Map<String, Object> data = MapUtils.build();
        data.put("orderUuid", orderDto.getUuid());
        data.put("title", "发生账单");
        data.put("typeModule", orderDto.getTypeModule());
        data.put("content", "司机已确认费用，请及时支付");
        PushContent pushContent = PushContent.newInstance4Pas(crosstownOrderParam.getAppid(), PushContent.ORDER_JOIN_PAS_ORDER_WAIT_PAS_PAY, data);
        pushService.sendMessage(orderDto.getPassengerUuid(), pushContent);

        if (isComplete) {
            //全部到达时 记录状态周期
            ThreadExecutorUtils.execute(new DriverStatusCycleRunnable(
                    driverStatusCycleService,
                    locationService,
                    orderDto.getAppid(),
                    orderDto.getActualDriverUuid(), orderDto.getMainOrderUuid(),
                    orderDto.getCarUuid(),
                    DriverStatusCycleDto.ACTION_SERVICE_OVER));
        }

        return ResponseData.buildSuccessResponse("操作成功", null);
    }


    /**
     * 订单信息异常校验
     */
    private ResponseData orderInfoVerify(OrderDto orderDto, Integer joinStatus) {
        if (null == orderDto) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "操作失败：获取订单信息失败");
        }
        //校验
        if (orderDto.getCloseStatus() == OrderConstant.ORDER_CLOSE_STATUS_CLOSED) {
            return ResponseData.buildErrorResponse(ORDER_CROSS_STATUS_CHANGE_ORDER_CLOSE.getCode(), ORDER_CROSS_STATUS_CHANGE_ORDER_CLOSE.getMsg());
        }
        boolean statusVerify = true;
        switch (joinStatus) {
            //行程开始
            case OrderConstant.ORDER_JOIN_STATUS_DRIVER_DEPARTURE:
                if (orderDto.getJoinStatus() != OrderConstant.ORDER_JOIN_STATUS_WAIT_START) {
                    statusVerify = false;
                }
                break;
            case OrderConstant.ORDER_JOIN_STATUS_ARRIVE_POINT:
                if (orderDto.getJoinStatus() != OrderConstant.ORDER_JOIN_STATUS_DRIVER_DEPARTURE) {
                    statusVerify = false;
                }
                break;
            //乘客上车（已取件）
            case OrderConstant.ORDER_JOIN_STATUS_PASSENGER_ABOARD:
                if (orderDto.getJoinStatus() != OrderConstant.ORDER_JOIN_STATUS_ARRIVE_POINT) {
                    statusVerify = false;
                }
                break;
            //到达目的地
            case OrderConstant.ORDER_JOIN_STATUS_COMPLETED:
                if (orderDto.getJoinStatus() != OrderConstant.ORDER_JOIN_STATUS_STARTED) {
                    statusVerify = false;
                }
                break;
            //司机选择收现
            case OrderConstant.ORDER_JOIN_STATUS_DRIVER_PAY:
                if (orderDto.getJoinStatus() != OrderConstant.ORDER_JOIN_STATUS_CONFIRM_FARE) {
                    statusVerify = false;
                }
                break;
            //发生账单给乘客支付
            case OrderConstant.ORDER_JOIN_STATUS_PASSENGER_PAY:
                if (orderDto.getJoinStatus() != OrderConstant.ORDER_JOIN_STATUS_CONFIRM_FARE) {
                    statusVerify = false;
                }
                break;
            default:
                statusVerify = false;
                break;
        }
        if (!statusVerify) {
            return ResponseData.buildErrorResponse(ORDER_CROSS_STATUS_CHANGE_ERROR.getCode(), ORDER_CROSS_STATUS_CHANGE_ERROR.getMsg());
        }
        return ResponseData.buildSuccessResponse("校验通过", true);
    }

    /**
     * 获取订单详情
     */
    private List<AllPassengerOrderVo> getAllPassengerOrder(CrosstownOrderParam crosstownOrderParam) {
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("mainOrderUuid", crosstownOrderParam.getMainOrderUuid());
        paraMap.put("closeStatus", OrderConstant.ORDER_CLOSE_STATUS_NORMAL);

        return orderMapper.allPassengerOrderInfo(paraMap);
    }


    /**
     * 完成订单费用结算
     */
    public ResponseData<BigDecimal> orderFareSettlement(OrderDto orderDto) {
        DriverVo driverVo = driverService.selInfo(orderDto.getActualDriverUuid()).getData();
        //获取司机
        if (driverVo == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取不到司机信息");
        }
        //抽成、流水、司机收入 —— 非收现类型订单
        //现金支付不记流水、不抽成
        // TODO: 后付款类型可以利用司机代付弥补、跨城先支付司机无入口给乘客代付，无法计算抽成
        PayVo payVo = null;
        //第三方支付、获取预支付补充
        if (orderDto.getPayType() == OrderConstant.PAY_TYPE_TENPAY || orderDto.getPayType() == OrderConstant.PAY_TYPE_ALIPAY) {
            Map<String, Object> build = MapUtils.build();
            build.put("orderUuid", orderDto.getUuid());
            build.put("status", FinancePrepayDto.STATUS_PAID);
            FinancePrepayDto financePrepayDto = financePrepayService.get(build).getData();
            if (financePrepayDto == null) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "操作失败：获取关联子订单预支付信息失败");
            }
            try {
                payVo = JsonUtils.readValue(financePrepayDto.getParams(), PayVo.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {//余额支付、非第三方（微信、支付宝）支付
            payVo = new PayVo(OrderConstant.PAY_PURPOSE_CHARGE_FARE, CommonConstant.PASSENGER, orderDto.getPayType(), orderDto.getPassengerUuid(), orderDto.getUuid(), null, null, orderDto.getAppid(), null, null);
            payVo.setOrderDto(orderDto);
            //获取乘客uuid
            PassengerVo passengerVo = new PassengerVo();
            passengerVo.setUuid(orderDto.getPassengerUuid());
            payVo.setPassengerVo(passengerVo);
            //获取订单价格
            OrderFareDto orderFareDto = orderFareService.get(MapUtils.build("orderUuid", payVo.getOrderUuid())).getData();
            if (orderFareDto == null) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "获取不到订单价格信息");
            }
            payVo.setOrderFareDto(orderFareDto);
        }
        payVo.setDriverVo(driverVo);
        DriverCommissionConfigDto driverCommissionConfigDto = driverService.getDriverCommissionConfig(orderDto.getActualDriverUuid()).getData();
        if (driverCommissionConfigDto != null) {
            log.info("获取到司机单独的佣金配置:{}", JsonUtils.toJSONString(driverCommissionConfigDto));
            payVo.setDriverCommissionConfigDto(driverCommissionConfigDto);
        }
        //计算抽成
        commissionProcessor.process(payVo);
        /* 更新乘客&司机成单量 */
        //乘客成单量+1
        passengerService.incrPasOrderCountByUuid(orderDto.getPassengerUuid());
        //司机成单量+1
        driverService.incrDriOrderCountByUuid(orderDto.getActualDriverUuid());
        return ResponseData.buildSuccessResponse(payVo.getOrderBalance());
    }

    /**
     * 通知其他乘客订单信息变更
     */
    public void pushOtherPassenger(CrosstownOrderParam crosstownOrderParam) {
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("mainOrderUuid", crosstownOrderParam.getMainOrderUuid());
        paraMap.put("closeStatus", OrderConstant.ORDER_CLOSE_STATUS_NORMAL);

        List<AllPassengerOrderVo> list = orderMapper.allPassengerOrderInfo(paraMap);
        if (list != null && list.size() > 0) {
            log.info("-------------执行推送其他拼友信息3-------------");
            List<String> passengerUuidList = new ArrayList<>();
            for (AllPassengerOrderVo allPassengerOrderVo : list) {
                if (!allPassengerOrderVo.getOrderUuid().equals(crosstownOrderParam.getOrderUuid())
                        && allPassengerOrderVo.getJoinStatus() < OrderConstant.ORDER_JOIN_STATUS_COMPLETED) {
                    passengerUuidList.add(allPassengerOrderVo.getPassengerUuid());
                }
            }
            /*消息推送*/
            Map<String, Object> data = MapUtils.build();
            data.put("orderUuid", crosstownOrderParam.getOrderUuid());
            data.put("mainOrderUuid", crosstownOrderParam.getMainOrderUuid());
            data.put("title", "行程信息更新通知");
            data.put("content", "拼友信息已更新，您可在订单查看订单最新动态");
            PushContent pushContent = PushContent.newInstance4Pas(crosstownOrderParam.getAppid(), PushContent.ORDER_JOIN_PAS_ORDER_REFRESH, data);
            log.info("-------------执行推送其他拼友信息4{}-------------",JsonUtils.toJSONString(pushContent));
            pushService.sendMessageByList(passengerUuidList, pushContent);
        }
    }

    /**
     * 权重分计算
     *
     * @param sysAssignConfigDto 计价规则
     * @param curOrderDetail     原订单明细
     * @param resNum             剩余座位
     * @param allOrderList       主单下的所有订单
     */
    public Double calWeightScore(SysAssignConfigDto sysAssignConfigDto, OrderDetailDto curOrderDetail, Integer resNum, List<AllPassengerOrderVo> allOrderList) {
        try {
            //订单起点经纬度
            double originMaxDistance = 0d;
            //订单终点经纬度
            double destMaxDistance = 0d;
            //订单出发时间
            long departTimeMaxInterval = 0L;
            //乘客人数
            int passengerNum = 0;
            for (AllPassengerOrderVo passengerOrderInfo : allOrderList) {
                //计算起终点直线距离
                Double originDistance = LocationUtils.getLineDistance(curOrderDetail.getOriginLng(), curOrderDetail.getOriginLat(), passengerOrderInfo.getOriginLng(), passengerOrderInfo.getOriginLat()) / 1000;
                log.info("{}起点距离{}", passengerOrderInfo.getOrderUuid(), originDistance);
                Double destDistance = LocationUtils.getLineDistance(curOrderDetail.getDestLng(), curOrderDetail.getDestLat(), passengerOrderInfo.getDestLng(), passengerOrderInfo.getDestLat()) / 1000;
                log.info("{}终点距离{}", passengerOrderInfo.getOrderUuid(), destDistance);
                //计算出发时间差值
                Long departTimeInterval = Math.abs(curOrderDetail.getDeparTime().getTime() - passengerOrderInfo.getDeparTime().getTime()) / (1000 * 60);
                log.info("{}出发时间差{}", passengerOrderInfo.getOrderUuid(), departTimeInterval);
                //比较差值 取出最大的
                originMaxDistance = originDistance > originMaxDistance ? originDistance : originMaxDistance;
                destMaxDistance = destDistance > destMaxDistance ? destDistance : destMaxDistance;
                departTimeMaxInterval = departTimeInterval > departTimeMaxInterval ? departTimeInterval : departTimeMaxInterval;
                passengerNum = passengerNum + passengerOrderInfo.getPassengerNum();
            }
            /**
             * 权重得分 = （1-originMaxDistance/配置起点范围)*配置起点权重
             * + (1-destMaxDistance/配置终点范围)*配置终点权重
             * +(1-departTimeInterval/配置出发时间范围)*配置出发时间权重 +0.5 + 上座率加分
             */
            Double weightScore = (1 - originMaxDistance / sysAssignConfigDto.getOriginRange()) * (sysAssignConfigDto.getOriginWeight() / 100)
                    + (1 - destMaxDistance / sysAssignConfigDto.getDestRange()) * (sysAssignConfigDto.getDestWeight() / 100)
                    + (1 - departTimeMaxInterval / sysAssignConfigDto.getDepartTimeRange()) * (sysAssignConfigDto.getDepartTimeWeight() / 100) + 0.5
                    + (passengerNum / (resNum + passengerNum) >= 0.6 ? (sysAssignConfigDto.getBeatRateBonus() / 100) : 0);
            log.info("originMaxDistance:{},destMaxDistance:{},departTimeMaxInterval:{},", originMaxDistance, destMaxDistance, departTimeMaxInterval);
//            return BigDecimal.valueOf(weightScore * 100).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            return BigDecimal.valueOf(weightScore * 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("订单:{}:计算权重异常", allOrderList.get(0).getOrderUuid());
        }
        return 0d;
    }

    /**
     * 检查订单是否已已上车或者都已完成 并更新主订单状态
     *
     * @param joinStatus
     * @param mainOrderUuid
     */
    public boolean verifyOrderStatus(Integer joinStatus, String mainOrderUuid) {
        boolean isComplete = false;
        Map<String, Object> verifyMap = new HashMap<>();
        verifyMap.put("mainOrderUuid", mainOrderUuid);
        switch (joinStatus) {
            //校验是否都已上车
            case OrderConstant.ORDER_JOIN_STATUS_ARRIVE_POINT: {
                verifyMap.put("joinStatus", OrderConstant.ORDER_JOIN_STATUS_PASSENGER_ABOARD);
                int notGetOnCount = orderMapper.verifyCrosstownOrderStatus(verifyMap);
                if (notGetOnCount == 0) {
                    //更新主单与子单的订单状态为行程中 500
                    orderMapper.updateStatusByJoinOrderRelatedUuid(mainOrderUuid, OrderConstant.ORDER_JOIN_STATUS_STARTED);
                    isComplete = true;
                }
                break;
            }

            //当订单为先付费是 校验是否都已完成 是则更新主单为已完成 当订单为后付费时 校验是否都已确认费用 是则更新状态为 部分未支付
            case OrderConstant.ORDER_JOIN_STATUS_STARTED: {
                verifyMap.put("joinStatus", OrderConstant.ORDER_JOIN_STATUS_COMPLETED);
                int notCompleteCount = orderMapper.verifyCrosstownOrderStatus(verifyMap);
                if (notCompleteCount == 0) {
                    updateMainOrderInfo(mainOrderUuid, OrderConstant.ORDER_JOIN_STATUS_COMPLETED);
                    isComplete = true;
                } else {
                    verifyMap.put("joinStatus", OrderConstant.ORDER_JOIN_STATUS_PASSENGER_PAY);
                    int notPay = orderMapper.verifyCrosstownOrderStatus(verifyMap);
                    if (notPay == 0) {
                        updateMainOrderInfo(mainOrderUuid, OrderConstant.ORDER_JOIN_STATUS_PART_NO_PAY);
                        isComplete = true;
                    }
                }
                break;
            }

            //待确认费用状态时  需要判断是否都已确认费用 是则更新为540部分未支付
            case OrderConstant.ORDER_JOIN_STATUS_CONFIRM_FARE: {
                verifyMap.put("joinStatus", OrderConstant.ORDER_JOIN_STATUS_DRIVER_PAY);
                int notCompleteCount = orderMapper.verifyCrosstownOrderStatus(verifyMap);
                if (notCompleteCount == 0) {
                    updateMainOrderInfo(mainOrderUuid, OrderConstant.ORDER_JOIN_STATUS_PART_NO_PAY);
                    isComplete = true;
                }
                break;
            }

            case OrderConstant.ORDER_JOIN_STATUS_COMPLETED: {
                verifyMap.put("joinStatus", OrderConstant.ORDER_JOIN_STATUS_COMPLETED);
                int notCompleteCount = orderMapper.verifyCrosstownOrderStatus(verifyMap);
                if (notCompleteCount == 0) {
                    updateMainOrderInfo(mainOrderUuid, OrderConstant.ORDER_JOIN_STATUS_COMPLETED);
                    isComplete = true;
                }
                break;
            }

            default:
                break;

        }
        return isComplete;
    }

    //根据子单状态更新主单信息
    private void updateMainOrderInfo(String mainOrderUuid, Integer joinStatus) {
        OrderDto mainOrder = new OrderDto();
        mainOrder.setUuid(mainOrderUuid);
        mainOrder.setJoinStatus(joinStatus);
        orderMapper.edit(mainOrder);

        OrderFareDto orderFareDto = new OrderFareDto();
        orderFareDto.setOrderUuid(mainOrderUuid);
        orderFareDto.setArriveTime(new Date());
        orderFareMapper.edit(orderFareDto);
    }

    /**
     * 操作加锁
     */
    public ResponseData handleLock(String mainOrderUuid) {
        String redisKey = "handleOrder" + mainOrderUuid;
        Long count = redisStringCacheService.incr(redisKey);
        if (count > 1) {
            redisStringCacheService.expire(redisKey, 1, TimeUnit.SECONDS);
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "系统繁忙，请稍后操作");
        }
        redisStringCacheService.expire(redisKey, 2, TimeUnit.SECONDS);
        return ResponseData.buildSuccessResponse("加锁成功");
    }

    /**
     * 处理改派主单信息
     */
    public void handleChangeAssignMainOrder(OrderDto orderDto, OrderDetailDto orderDetailDto, boolean isParcelOrder) {
        Map<String, Object> build = MapUtils.build();
        build.put("orderUuid", orderDto.getMainOrderUuid());
        build.put("byUnCompleted", 1);
        List<OrderDto> orders = orderMapper.findRelatedByOrderUuid(build);
        boolean existNormalOrder = orders.stream().filter(dto -> ORDER_TYPE_CHILD.equals(dto.getTypeMain())).filter(dto ->
                ORDER_CLOSE_STATUS_NORMAL == dto.getCloseStatus()).findFirst().isPresent();
        if (!existNormalOrder) {
            //更新拼车（主&子）订单关闭状态
            orderMapper.closeStatusByJoinOrderRelatedUuid(orderDto.getMainOrderUuid(), ORDER_CLOSE_STATUS_CLOSED);
        } else {
            //待上车被关闭或者行程中被关闭 需要判断主订单下的未关闭订单是否都未已到达或者已上车 是则更新主订单状态
            if (orderDto.getJoinStatus() == ORDER_JOIN_STATUS_ARRIVE_POINT || orderDto.getJoinStatus() == ORDER_JOIN_STATUS_STARTED) {
                verifyOrderStatus(orderDto.getJoinStatus(), orderDto.getMainOrderUuid());
            }
        }
        //非跨城小件订单时 还原订单座位 跨城小件订单减少主单的跨城订单数
        if (StringUtils.isNotEmpty(orderDto.getMainOrderUuid())) {
            OrderDetailDto mainOrderDetailDto = findOrderDetail(orderDto.getMainOrderUuid());
            OrderDto mainOrder = findOrder(orderDto.getMainOrderUuid());
            if (null != mainOrder && null != mainOrderDetailDto) {
                if (isParcelOrder) {
                    mainOrderDetailDto.setParcelOrderNum(mainOrderDetailDto.getParcelOrderNum() - 1);
                } else {
                    mainOrder.setSeatNum(mainOrder.getSeatNum() - orderDto.getSeatNum());
                    saveOrUpdate(mainOrder);
                    mainOrderDetailDto.setActualPasNum(mainOrderDetailDto.getActualPasNum() - orderDetailDto.getActualPasNum());
                    mainOrderDetailDto.setAdultNum(mainOrderDetailDto.getAdultNum() - orderDetailDto.getAdultNum());
                    mainOrderDetailDto.setResNum(mainOrderDetailDto.getResNum() + orderDto.getSeatNum());
                    //获取被指派订单关联子订单
                    List<Date> subDeparTimes = orderMapper.findSubDeparTime(mainOrderDetailDto.getUuid());
                    if (CollectionUtils.isNotEmpty(subDeparTimes)) {
                        mainOrderDetailDto.setDeparTime(subDeparTimes.get(subDeparTimes.size() - 1));
                    }
                }
                orderDetailService.saveOrUpdate(mainOrderDetailDto);
            }
        }
    }
}
